<template>
  <div class="pay-result-bg">
    <el-card class="pay-result-card">
      <div class="pay-result-header">
        <el-button @click="goHome" icon="House">返回首页</el-button>
        <div class="pay-result-title">支付结果</div>
      </div>
      <div v-if="loading">正在确认支付结果...</div>
      <div v-else>
        <el-result
          :icon="success ? 'success' : 'warning'"
          :title="success ? '支付成功' : '支付检查中'"
          :sub-title="success ? '订单已支付完成，正在跳转...' : '正在检查支付状态...'"
        >
          <template #extra>
            <div v-if="success">
              <el-button type="primary" @click="goDetail">立即查看订单详情</el-button>
              <el-button @click="goHome">返回首页</el-button>
            </div>
            <div v-else>
              <el-button
                type="success"
                @click="manualConfirmPayment"
                :loading="confirmLoading"
                style="margin-right: 10px;"
              >
                我已完成支付，确认支付成功
              </el-button>
              <el-button @click="goDetail">返回订单详情</el-button>
            </div>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '../utils/request'
import { orderAPI } from '@/api/order'
import axios from "axios";

const route = useRoute()
const router = useRouter()
const orderId = route.query.order_id
const loading = ref(true)
const success = ref(false)
const orderid = ref(0)
const confirmLoading = ref(false)

async function checkPay() {
  try {
    // 轮询检查支付状态，最多检查10次，每次间隔2秒
    let attempts = 0
    const maxAttempts = 3
    
    while (attempts < maxAttempts) {
      const res = await orderAPI.getOrders({ order_number: orderId })
      if (res.data && res.data.length > 0) {
        const order = res.data[0]
        orderid.value = order.id
        if (order.order_status === 4) { // 4=已支付
          success.value = true
          loading.value = false
          // 通知主页更新统计数据
          localStorage.setItem('statsNeedRefresh', Date.now().toString())
          return
        }
      }
      
      attempts++
      if (attempts < maxAttempts) {
        await new Promise(resolve => setTimeout(resolve, 2000)) // 等待2秒
      }
    }
    
    // 如果轮询结束仍未支付成功
    success.value = false
  } catch (error) {
    console.error('检查支付状态失败:', error)
    success.value = false
  } finally {
    loading.value = false
  }
}
function goDetail() {
  router.replace(`/order/detail/${orderid.value}`)
}

function goHome() {
  router.push('/')
}

// 手动确认支付成功
async function manualConfirmPayment() {
  if (!orderId) {
    ElMessage.error('订单号不存在')
    return
  }

  confirmLoading.value = true

  try {
    const response = await http.post('/order/manual/payment/success/', {
      order_number: orderId
    })

    console.log('手动确认支付结果:', response.data)

    // 检查响应格式 - 支持多种响应格式
    if (response.data.msg === 'success' || response.data.msg === '支付成功处理完成') {
      ElMessage.success('支付确认成功，司机余额已更新')
      
      // 设置支付成功状态
      success.value = true
      
      // 获取订单ID用于跳转
      try {
        const res = await orderAPI.getOrders({ order_number: orderId })
        if (res.data && res.data.length > 0) {
          orderid.value = res.data[0].id
        }
      } catch (orderError) {
        console.error('获取订单信息失败:', orderError)
        // 即使获取订单信息失败，也继续处理
      }

      // 通知主页更新统计数据
      localStorage.setItem('statsNeedRefresh', Date.now().toString())
      
      // 延迟跳转到订单详情页面
      setTimeout(() => {
        if (orderid.value) {
          router.replace(`/order/detail/${orderid.value}`)
        } else {
          router.push('/')
        }
      }, 1500)
      
    } else if (response.data.already_paid) {
      ElMessage.info('订单已支付')
      success.value = true
      
      // 获取订单ID并跳转
      try {
        const res = await orderAPI.getOrders({ order_number: orderId })
        if (res.data && res.data.length > 0) {
          orderid.value = res.data[0].id
          setTimeout(() => {
            router.replace(`/order/detail/${orderid.value}`)
          }, 1500)
        }
      } catch (orderError) {
        console.error('获取订单信息失败:', orderError)
      }
      
    } else {
      ElMessage.error('确认支付失败')
    }
  } catch (error) {
    console.error('手动确认支付失败:', error)
    ElMessage.error(error.response?.data?.error || '确认支付失败，请重试')
  } finally {
    confirmLoading.value = false
  }
}

onMounted(checkPay)
</script>

<style scoped>
.pay-result-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fff 60%, #e6f7ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.pay-result-card {
  width: 480px;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 32px 36px 24px 36px;
  position: relative;
}
.pay-result-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.pay-result-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 2px;
}
</style>